from bs4 import BeautifulSoup
from typing import Optional, Dict, Any
import re

class CourseParser:
    """
    课程信息解析类，用于从HTML内容中提取课程相关信息
    """
    
    def __init__(self, html_content: str):
        """
        初始化解析器
        
        Args:
            html_content: HTML页面内容
        """
        self.soup = BeautifulSoup(html_content, 'lxml')
        # 修复：查找包含课程信息的ul元素下的所有li元素
        course_ul = self.soup.find('ul', class_='w_top_vidio_ul')
        self.info_elements = course_ul.find_all('li') if course_ul else []
        
    def get_course_name(self) -> Optional[str]:
        """
        获取课程名称
        
        Returns:
            str: 课程名称，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '课程：' in text:
                return text.replace('课程：', '').strip()
        return None
    
    def get_teacher_name(self) -> Optional[str]:
        """
        获取教师姓名
        
        Returns:
            str: 教师姓名，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '教师：' in text:
                return text.replace('教师：', '').strip()
        return None
    
    def get_classroom(self) -> Optional[str]:
        """
        获取教室信息
        
        Returns:
            str: 教室信息，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '教室：' in text:
                return text.replace('教室：', '').strip()
        return None
    
    def get_class_name(self) -> Optional[str]:
        """
        获取班课名称
        
        Returns:
            str: 班课名称，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '班课：' in text:
                return text.replace('班课：', '').strip()
        return None
    
    def get_student_count(self) -> Optional[int]:
        """
        获取学生人数
        
        Returns:
            int: 学生人数，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '人数：' in text:
                count_text = text.replace('人数：', '').replace('人', '').strip()
                try:
                    return int(count_text)
                except ValueError:
                    return None
        return None
    
    def get_course_time(self) -> Optional[Dict[str, str]]:
        """
        获取课程时间
        
        Returns:
            Dict[str, str]: 包含日期和周次的字典，如果未找到返回None
        """
        for element in self.info_elements:
            text = element.get_text(strip=True)
            if '上课时间：' in text:
                # 修复：更精确的正则表达式匹配
                date_match = re.search(r'上课时间：(\d{4}-\d{2}-\d{2})', text)
                weeks_match = re.search(r'排课周：(\d+-\d+周)', text)
                if date_match:
                    result = {'date': date_match.group(1)}
                    if weeks_match:
                        result['weeks'] = weeks_match.group(1)
                    return result
        return None
    
    def get_all_info(self) -> Dict[str, Any]:
        """
        获取所有课程信息
        
        Returns:
            Dict包含所有提取的信息
        """
        return {
            'course_name': self.get_course_name(),
            'teacher_name': self.get_teacher_name(),
            'classroom': self.get_classroom(),
            'class_name': self.get_class_name(),
            'student_count': self.get_student_count(),
            'course_time': self.get_course_time()
        }


def example_usage():
    html_content = """
    <body style="zoom: 1;">
<div style="position: relative;">
    <div class="w_top_vidio">
        <div class="w_wrap">
                                                                                    <div class="fr w_show_btn"><a style="color:red;" id="qiehuan" href="javascript:void(0);" onclick="changeOtherViewUrl();">切换源流播放</a></div>&nbsp;&nbsp;&nbsp;&nbsp;
            <ul class="w_top_vidio_ul">
                <li style="display: none" id="countxs"><a href="javascript:void(0);"><i id="countdown" style="color: red"></i></a>
                </li>
                <li><a href="javascript:void(0);"><i class="">课程：</i>机器人控制</a></li>
                <li><a href="javascript:void(0);">教师：杜敬利</a></li>
                <li><a href="javascript:void(0);">教室：J-404</a></li>
                <li><a href="javascript:void(0);">班课：机器人控制01</a></li>
                <li><a href="javascript:void(0);">人数：6人</a></li>
                <li><a href="javascript:void(0);">上课时间：2025-04-01
                    &nbsp;&nbsp;&nbsp;&nbsp;排课周：2-17周</a></li>

            </ul>
        </div>
    </div>
</div>
    </body>
    """
    
    # 创建解析器实例
    parser = CourseParser(html_content)
    
    # 获取各项信息
    print(f"课程名称: {parser.get_course_name()}")
    print(f"教师姓名: {parser.get_teacher_name()}")
    print(f"教室: {parser.get_classroom()}")
    print(f"班课名称: {parser.get_class_name()}")
    print(f"学生人数: {parser.get_student_count()}")
    print(f"课程时间: {parser.get_course_time()}")
    
    # 或者一次性获取所有信息
    print("\n所有信息:")
    all_info = parser.get_all_info()
    for key, value in all_info.items():
        print(f"{key}: {value}")


if __name__ == "__main__":
    example_usage()